package com.blunka.framework.client.ui.dialog;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.MatteBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.blunka.framework.client.constants.DesignConstant;
import com.blunka.framework.client.constants.InitDesignConfig;
import com.blunka.framework.client.db.druid.DBSQLService;
import com.blunka.framework.client.db.druid.service.ISQLService;
import com.blunka.framework.client.enums.ModelType;
import com.blunka.framework.client.ui.MainFrame;
import com.blunka.framework.client.ui.TreeModelPanel;
import com.blunka.framework.client.ui.entity.BlkTableMetaData;
import com.blunka.framework.client.utils.DesignUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;

/**
 * 属性创建窗体
 *
 * @author Administrator
 *
 */
public abstract class ProtyDialog{

	private static final Logger logger = Logger.getLogger(ProtyDialog.class);

	/**
	 * 数据库服务
	 */
	private static ISQLService sqlHepler = DBSQLService.getLocalDBService();
	
	/**
	 * 获取本地缓存数据库
	 */
	private static ISQLService localSqlHepler = DBSQLService.getLocalDBService();

	private JDialog dialog;

	private JPanel mainDialog;

	private JPanel gridPanel;

	private JPanel buttonPanel;

	private JLabel cnTextLabel; // 数据库类型

	private JTextField cnText;

	private JLabel enTextLabel; // 数据库驱动

	private JTextField enText; // 数据库驱动输入框

	private JTextField prefixText; // 前缀

	private String prefixValue; // 前缀名称

	public ProtyDialog(String title, ModelType modelType) {
		initDialog(title, modelType);
	}

	public String getEnText(){
		return prefixText.getText()+enText.getText();
	}

	public String getCnText(){
		return cnText.getText();
	}

	/**
	 * 初始化窗体
	 * @param title
	 * @param modelType
	 */
	private void initDialog(String title, ModelType modelType) {
		dialog = new JDialog();
		dialog.setTitle(title);


		dialog.setSize(new Dimension(350, 150));
		Container contentPanel = dialog.getContentPane();

		gridPanel = new JPanel();
		gridPanel.setLayout(null);

		cnTextLabel = new JLabel("节点名称：");
		cnTextLabel.setHorizontalAlignment(JLabel.RIGHT);
		cnText = new JTextField();
		gridPanel.add(cnTextLabel);
		gridPanel.add(cnText);
		cnTextLabel.setBounds(10, 10, 100, 25);
		cnText.setBounds(110, 10, 200, 25);

		enTextLabel = new JLabel("英文名称：");
		enTextLabel.setHorizontalAlignment(JLabel.RIGHT);

		prefixText = new JTextField();

		enText = new JTextField();
		gridPanel.add(enTextLabel);
		gridPanel.add(prefixText);
		gridPanel.add(enText);
		enTextLabel.setBounds(10, 40, 100, 25);
		prefixText.setBounds(110, 40, 50, 25);
		MatteBorder border = new MatteBorder(1, 1, 1, 0, new Color(192, 192, 192));
		prefixText.setBorder(border);
		prefixText.setEnabled(false);
		prefixText.setText(prefixValue);
		MatteBorder border2 = new MatteBorder(1, 0, 1, 1, new Color(192, 192, 192));
		enText.setBounds(160, 40, 150, 25);
		enText.setBorder(border2);
		enText.addFocusListener(new FocusListener() {
			@Override
			public void focusGained(FocusEvent arg0) {

			}

			@Override
			public void focusLost(FocusEvent arg0) {
				String text = enText.getText();
				if (!StringUtils.isEmpty(text)) {
					enText.setText(text.toUpperCase());
				}

			}

		});
		cnText.getDocument().addDocumentListener(addListener());

		buttonPanel = new JPanel();

		JButton buttonOK = new JButton("确   定");
		buttonOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (cnText.getText().trim().equals("")) {
					DesignUtils.showMessage(dialog, "请输入中文显示名称", "系统提示", JOptionPane.INFORMATION_MESSAGE);
					return;
				}
				if(DesignUtils.isSqlKeyWord(enText.getText().trim())) {
					DesignUtils.showMessage(dialog, "输入的英文名称不合法", "系统提示", JOptionPane.INFORMATION_MESSAGE);
					return;
				}
				try{
					TreeModelPanel treePanel = TreeModelPanel.newInstance();
					DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) treePanel.getTree().getLastSelectedPathComponent();
					BlkTableMetaData parentTableMetaData = (BlkTableMetaData)parentNode.getUserObject();

					BlkTableMetaData node = new BlkTableMetaData();
					node.setZh_cn(getCnText());
					node.setEn_us(getEnText());
					node.setModel_type(modelType);
					if(node.getModel_type() == ModelType.TABLE || node.getModel_type() == ModelType.VIEW){
						//表或者试图需要验证是否已经数据库建立
						if(sqlHepler.queryTableOrViewExists(node)){
							logger.error("节点属性【"+node.getEn_us()+",已经存在】,或者存在已删除的节点但是还没有提交，请先提交！");
							DesignUtils.showMessage(dialog, "属性【"+node.getEn_us()+",已经存在】",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
							return;
						}

					}else if(node.getModel_type() == ModelType.ATTRIBUTE){
						//字段属性所属表
						node.setFather_tablemetadata_id(parentTableMetaData.getTablemetadata_id());
						//字段需要验证在当前所有子节点下是否存在
						if(sqlHepler.queryTableOrViewFieldExists(node, parentTableMetaData.getEn_us())){
							logger.error("节点属性【"+node.getEn_us()+",已经存在】,或者存在已删除的节点但是还没有提交，请先提交！");
							DesignUtils.showMessage(dialog, "节点属性已经存在",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
							return;
						}
					}else {
						//系统模块，业务模块，组模块，需要判断当前节点的父节点下是否已经存在了节点信息
						if(sqlHepler.queryModelNodeExists(parentTableMetaData, node.getEn_us()) || localSqlHepler.queryModelNodeExists(parentTableMetaData, node.getEn_us())) {
							logger.error("节点属性【"+node.getEn_us()+",在同一目录下已经存在】！");
							DesignUtils.showMessage(dialog, "节点属性载同一目录下已经存在",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
							return;
						}
					}
					
					if(beforeCallBack(getCnText(),getEnText())) {
						dialog.dispose();
				    	//调用回调函数
				    	callBack(getCnText(),getEnText());
					}
				}catch(Exception ex){
					DesignUtils.showMessage(dialog, "执行异常,请查看日志面板异常信息!",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					logger.error(ex);
				}

			}
		});
		JButton buttonNo = new JButton("取   消");
		buttonNo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dialog.dispose();
				return;
			}
		});

		buttonPanel.add(buttonOK);
		buttonPanel.add(buttonNo);
		buttonOK.setBounds(200, 10, 100, 25);
		buttonNo.setBounds(250, 10, 100, 25);

		mainDialog = new JPanel();
		mainDialog.setLayout(new BorderLayout());
		mainDialog.add(new JScrollPane(gridPanel), BorderLayout.CENTER);
		contentPanel.setLayout(new BorderLayout());
		contentPanel.add(mainDialog, BorderLayout.CENTER);
		contentPanel.add(buttonPanel, BorderLayout.SOUTH);

		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultMutableTreeNode rootNode = treePanel.getSelectNodeRoot(treePanel.getSelectTreeNode());
		BlkTableMetaData rootModel = (BlkTableMetaData)rootNode.getUserObject();
		if(rootModel.getModel_type() == ModelType.SYSTEM){
			//判断顶层节点是否为系统
			if (modelType.getIndex() == ModelType.TABLE.getIndex()) {
				//表
				prefixValue = InitDesignConfig.getSystemTablePrefix();
			} else if (modelType.getIndex() == ModelType.VIEW.getIndex()) {
				//试图
				prefixValue = InitDesignConfig.getSystemViewPrefix();
			}else{
				prefixText.setVisible(false);
				MatteBorder v = new MatteBorder(1, 1, 1, 1, new Color(192, 192, 192));
				enText.setBounds(110, 40, 200, 25);
				enText.setBorder(v);
			}
		}else{
			//非系统
			if (modelType.getIndex() == ModelType.TABLE.getIndex()) {
				//表
				prefixValue = InitDesignConfig.getTablePrefix();
			} else if (modelType.getIndex() == ModelType.VIEW.getIndex()) {
				//试图
				prefixValue = InitDesignConfig.getViewPrefix();
			}else{
				prefixText.setVisible(false);
				MatteBorder v = new MatteBorder(1, 1, 1, 1, new Color(192, 192, 192));
				enText.setBounds(110, 40, 200, 25);
				enText.setBorder(v);
			}
		}


		prefixText.setText(prefixValue);
		showDialogModel();
	}

	/**
	 * 显示启动窗体
	 */
	private void showDialogModel(){
		dialog.setModal(true);
		dialog.setLocationRelativeTo(MainFrame.getMainFrame());
		dialog.setVisible(true);

	    String zhText = this.getCnText();
	    String enText = this.getEnText();
	    if(StringUtils.isEmpty(zhText) || StringUtils.isEmpty(enText)){
	    	return;
	    }


	}

	/**
	 * 键盘输入改变事件
	 *
	 * @return
	 */
	private DocumentListener addListener() {
		DocumentListener action = new DocumentListener() {

			@Override
			public void changedUpdate(DocumentEvent event) {
				setEnText();
			}

			@Override
			public void insertUpdate(DocumentEvent event) {
				setEnText();
			}

			@Override
			public void removeUpdate(DocumentEvent event) {
				setEnText();
			}
		};
		return action;
	}

	/**
	 * 根据获取的中文名称获取首字母
	 */
	private void setEnText() {
		String text = cnText.getText();
		try {
			String letter = getFirstLetter(text);
			enText.setText(letter.toUpperCase());
		} catch (Exception e) {
			logger.error("获取中文首字母异常", e);
		}
	}

	/**
	 * 获取中文首字母
	 *
	 * @param txt
	 * @return
	 */
	private String getFirstLetter(String str) throws Exception {
		String convert = "";
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word, new HanyuPinyinOutputFormat());
			if (pinyinArray != null) {
				convert += pinyinArray[0].charAt(0);
			} else {
				convert += word;
			}
		}
		return convert;
	}
	
	/**
	 * 窗体关闭之前执行方法
	 * @param zhText
	 * @param enText
	 * @return
	 */
	public abstract boolean beforeCallBack(String zhText,String enText)throws Exception;
	
	/**
	 * 新建节点属性窗体回调函数
	 * @param zhText
	 * @param enText
	 */
	public abstract void callBack(String zhText,String enText)throws Exception;

	/*public static void main(String args[]){
		try{
			BlkTableMetaData node = new BlkTableMetaData();
			node.setEn_us("T_CUS_YHXXB");
			boolean i = sqlHepler.queryTableOrViewExists(node);
			System.out.println("----->"+i);
		}catch(Exception e){
			logger.error("异常",e);
		}
	}*/
}
